<template>
	<view>
        <view class="goods-view">
            <view>
                <goods-info
                    :goodsPrice="sku.purchase_price"
                    :goodsName="sku.name"
                    :goodsImg="sku.goods_image"
                    :goodsSpecList="sku.spec_list"
                    :goodsNum="sku.num">
                </goods-info>
                <view class="u-flex u-row-between u-padding-left-15 u-padding-right-15">
                    <view>申请数量</view>
                    <view>
                        <u-number-box v-model="form.return_num" :min="1" :max="sku.num" @change="valChange"></u-number-box>
                    </view>
                </view>
            </view>
        </view>

        <view class="block-view">
            <u-field
                v-model="form.reason"
                input-align="right"
                label="申请原因"
                placeholder="请选择申请原因"
                placeholder-style="color: #CDCDCD"
                @click="onReason"
                disabled
                required
                right-icon="arrow-right"
                maxlength="20">
            </u-field>
            <view class="u-margin-top-15 u-margin-left-30 u-margin-right-20">
                <u-input v-model="form.problem_desc" :customStyle="remarkStyle" :type="'textarea'" :auto-height="true" placeholder="请描述申请售后服务的具体原因."/>
            </view>
            <!-- 上传图片 -->
            <view class="u-margin-top-10 u-margin-left-20">
                <u-upload :action="action" :header="header" :max-count="5" :file-list="fileList" @on-uploaded="onUploaded" ></u-upload>
            </view>
        </view>

        <view class="block-view" v-if="form.service_type === 'RETURN_GOODS'">
            <u-field v-model="form.return_way_str" disabled input-align="right" label="退款方式" placeholder-style="color: #CDCDCD"  maxlength="20"></u-field>
            <view v-if="!afterSaleData.is_retrace_balance && !afterSaleData.is_retrace">
                <u-field
                    v-model="form.account_type_str"
                    input-align="right"
                    label="账户类型"
                    placeholder="请选择账户类型"
                    placeholder-style="color: #CDCDCD"
                    @click="alterSaleWayShow = true"
                    disabled
                    right-icon="arrow-right"
                    maxlength="20"
                >
                </u-field>
                <u-field v-model="form.return_account" v-if="form.account_type != 'BANKTRANSFER' && form.account_type !== 'BALANCE'" input-align="right" label="退款账号" placeholder="请填写退款账号" placeholder-style="color: #CDCDCD"  maxlength="20"></u-field>
                <view v-if="form.account_type == 'BANKTRANSFER'">
                    <u-field v-model="form.bank_name" input-align="right" label="银行名称" placeholder="请填写银行名称" placeholder-style="color: #CDCDCD"  maxlength="20"></u-field>
                    <u-field v-model="form.bank_account_number" input-align="right" label="银行账号" placeholder="请填写银行账号" placeholder-style="color: #CDCDCD"  maxlength="20"></u-field>
                    <u-field v-model="form.bank_account_name" input-align="right" label="银行开户名" placeholder="请填写银行开户名" placeholder-style="color: #CDCDCD"  maxlength="20"></u-field>
                    <u-field v-model="form.bank_deposit_name" input-align="right" label="银行开户行" placeholder="请填写银行开户行" placeholder-style="color: #CDCDCD"  maxlength="20"></u-field>
                </view>
            </view>
        </view>

        <view class="block-view">
            <u-field input-align="right" disabled label="返回方式" value="快递至第三方卖家" placeholder-style="color: #CDCDCD"  maxlength="20"></u-field>
            <u-field v-model="form.apply_vouchers" input-align="right" disabled label="申请凭证" placeholder="请选择申请凭证" placeholder-style="color: #CDCDCD" right-icon="arrow-right" maxlength="20" @click="applyVouchersShow = true"></u-field>
            <u-field v-model="form.addrs" input-align="right" disabled label="收货地址" placeholder="请选择收货地区" placeholder-style="color: #CDCDCD" right-icon="arrow-right"  maxlength="20" @click="showAddressSelector = true"></u-field>
            <u-field v-model="form.ship_addr" input-align="right" label="详细地址" placeholder="请填写详细地址" placeholder-style="color: #CDCDCD"  maxlength="50"></u-field>
            <u-field v-model="form.ship_name" input-align="right" label="联系人" placeholder="请填写联系人" placeholder-style="color: #CDCDCD"  maxlength="20"></u-field>
            <u-field v-model="form.ship_mobile" input-align="right" label="联系方式" placeholder="请填写联系方式" placeholder-style="color: #CDCDCD"  maxlength="11"></u-field>
        </view>

        <view class="btn-view">
            <u-button type="error" shape="circle" @click="onSubmit">提交</u-button>
        </view>

        <!-- 申请原因 -->
        <u-popup class="block-popup" v-model="reasonShow" mode="bottom" length="80%">
            <view class="header">
                申请原因
            </view>
            <view class="body">
                <view class="title">
                    请选择申请原因（必选）：
                </view>
                <u-radio-group v-model="reason">
                    <view class="value">
                        <view class="radio-view" v-for="(item,index) in reasonList">
                            <u-radio active-color="red" label-size="31" shape="circle" :name="item.name" @change="reasonChange">{{item.name}}</u-radio>
                        </view>
                    </view>
                </u-radio-group>
            </view>
        </u-popup>

        <!-- 申请凭证 -->
        <u-popup class="block-popup" v-model="applyVouchersShow" mode="bottom" length="40%">
            <view class="header">
                申请凭证
            </view>
            <view class="body">
                <u-checkbox-group @change="checkboxGroupChange" :wrap="true">
                    <u-checkbox
                        v-model="item.checked"
                        v-for="(item, index) in vouchersList" :key="index"
                        :name="item.name"
                    >{{item.name}}</u-checkbox>
                </u-checkbox-group>
            </view>
        </u-popup>

        <!-- 地区选择器 -->
        <u-popup v-model="showAddressSelector" mode="bottom" closeable close-icon-size="20" border-radius="20">
            <region-picke @addressSelectorChanged="addressSelectorChanged" @closeRegionpicke="showAddressSelector = false" :show="showAddressSelector"></region-picke>
        </u-popup>

        <u-select v-model="alterSaleWayShow" :list="alterSaleWayList" @confirm="alterSaleWayChange"></u-select>
        <u-toast ref="uToast" />
	</view>
</template>

<script>
    import * as API_AfterSale from '@/api/after-sale.js'
    import { api } from '@/config/config.js'
    import { RegExp } from '@/ui-utils'
    import Cache,{Keys} from '@/utils/cache.js'

    const that = this;
	export default {
		data() {
			return {
                action: `${api.buyer}/uploaders`,
                header:  { Authorization: Cache.getItem(Keys.accessToken) },
                value: 1,
                remarkStyle: {
                    backgroundColor: '#f3f4f6',
                    borderRadius: '10rpx',
                    padding: '10rpx',
                },
                sku: {},
                sn: '',
                reason: '',
                reasonShow: false,
                applyVouchersShow: false,
                showAddressSelector: false, //地区选择弹出框是否显示
                reasonList: [{
                        name: '商品质量有问题',
                        disabled: false
                    },
                    {
                        name: '收到商品与描述不符',
                        disabled: false
                    },
                    {
                        name: '不喜欢/不想要',
                        disabled: false
                    },
                    {
                        name: '发票问题',
                        disabled: false
                    },
                    {
                        name: '空包裹',
                        disabled: false
                    },
                    {
                        name: '快递无记录',
                        disabled: false
                    },
                    {
                        name: '快递一直没有收到',
                        disabled: false
                    },
                    {
                        name: '买错/不想要',
                        disabled: false
                    },
                    {
                        name: '未按照时间发货',
                        disabled: false
                    },
                    {
                        name: '其他',
                        disabled: false
                }],
                vouchersList: [{
                    name: '有发票',
                    checked: false,
                    disabled: false
                },{
                    name: '有检测报告',
                    checked: false,
                    disabled: false
                }],
                type:'money',   //申请售后类型, money：申请退款
                alterSaleWayShow: false,
                alterSaleWayList: [{
						value: 'ALIPAY',
						label: '支付宝'
					},{
						value: 'WEIXINPAY',
						label: '微信'
					},{
						value: 'BANKTRANSFER',
						label: '银行转账'
                },{
						value: 'BALANCE',
						label: '预存款'
                }],
                form: {
                    reason: '',         //申请原因
                    return_num: 1,      //退货数量
                    ship_addr: '',      //详细地址
                    ship_name: '',      //联系人
                    ship_mobile: '',    //联系电话
                    account_type: '',   //账户类型
                    problem_desc: '',   //问题描述
                    return_account: '', //退款账号
                    order_sn: '',       //订单编号
                    sku_id: 0,          //skuid
                    service_type: 'RETURN_GOODS',   //申请类型
                    apply_vouchers: '', //凭证
                    region: 0,       //地区ID
                    images: [],         //图片
                    return_way_str: '账号退款',
                },
                fileList: [],
                afterSaleData: {},
			};
		},
        onLoad(options) {
            this.sku = JSON.parse(decodeURIComponent(options.sku));
            this.form.sku_id = this.sku.sku_id;
            this.form.order_sn = options.sn;
            let navTitle = '申请退货';
            if(options.type == 1){
                navTitle = '申请退货'
                this.form.service_type = 'RETURN_GOODS';
            } else if(options.type == 2) {
                navTitle = '申请换货'
                this.form.service_type = 'CHANGE_GOODS';
            } else if(options.type == 3) {
                navTitle = '申请补发'
                this.form.service_type = 'SUPPLY_AGAIN_GOODS';
            }
            uni.setNavigationBarTitle({
                title: navTitle
            });

            this.loadData();
        },
        methods: {
            valChange(e) {
                console.log('当前值为: ' + e.value)
            },
            onUploaded(list){
                this.form.images = [];
                list.forEach(res => {
                    this.form.images.push(res.response.url)
                })
            },
            onReason() {
                this.reasonShow = true;
            },
            //申请原因
            reasonChange(reason) {
                this.form.reason = reason;
                this.reasonShow = false;
            },
            //账户类型
            alterSaleWayChange(e){
                this.form.account_type = e[0].value;
                this.form.account_type_str = e[0].label;
            },
            // 申请凭证选择
            checkboxGroupChange(e) {
                this.form.apply_vouchers = e.toString();

            },
            //地址发生变化
            addressSelectorChanged(object) {
                const obj = {
                    last_id: object[object.length - 1].id,
                    addrs: object.map(key => { return key.local_name }).join(' ')
                }
                this.form.region = obj.last_id
                this.form.addrs = obj.addrs
            },
            loadData(){
                //读取信息
                API_AfterSale.getAfterSaleData(this.form.order_sn,this.form.sku_id).then(res => {
                    this.form.addrs = `${res.province}${res.city}${res.county}${res.town}`
                    this.form.region = res.town_id == 0 ? res.county_id : res.town_id
                    this.form.ship_addr = res.ship_addr
                    this.form.ship_name = res.ship_name
                    this.form.ship_mobile = res.ship_mobile
                    this.form.return_num = res.buy_num
                    this.afterSaleData = res;

                    if(res.is_retrace){
                        this.form.return_way_str = '原路退回'
                    }
                    if(res.is_retrace_balance){
                        this.form.return_way_str = '预存款退款'
                    }

                })
            },
            onSubmit(){
                if (!this.handleCheckParams()) {
                    return
                }
                if(this.form.service_type === 'RETURN_GOODS'){
                    let {account_type_str, ...params} = this.form;
                    API_AfterSale.applyAfterSaleGoods(params).then(afterCallback)
                }
                if(this.form.service_type === 'CHANGE_GOODS'){
                    let {account_type_str, ...params} = this.form;
                    API_AfterSale.applyAfterSaleChange(params).then(afterCallback)
                }
                if(this.form.service_type === 'SUPPLY_AGAIN_GOODS'){
                    let {account_type_str, ...params} = this.form;
                    API_AfterSale.applyAfterSaleReplace(params).then(afterCallback)
                }

                async function afterCallback(response) {
                    uni.showToast({
                        title: '提交成功'
                    })
                    setTimeout(()=>{
                    	uni.navigateTo({
                    	    url: '/order-module/order/after-sale/after-sale'
                    	})
                    }, 1500)

                }
            },
            handleCheckParams(){
                if (!this.form.reason || this.form.reason === '请选择申请原因') {
                    this.$u.toast('请选择申请原因！')
                    return
                }
                if (!this.form.problem_desc) {
                    this.$u.toast('请输入问题描述！')
                    return
                }
                if (!this.afterSaleData.is_retrace_balance && !this.afterSaleData.is_retrace) {
                    if (this.form.service_type === 'RETURN_GOODS') {
                        if (!this.form.account_type) {
                           this.$u.toast('请选择账户类型！')
                           return
                        }
                        // 如果账户类型不为银行卡
                        if (this.form.account_type === 'BANKTRANSFER') {
                            // 银行名称校验
                            if (!this.form.bank_name) {
                                this.$u.toast('请输入银行名称！')
                                return
                            }
                            // 银行账号校验
                            if (!this.form.bank_account_number) {
                               this.$u.toast('请输入银行账号！')
                               return
                            }
                            // 银行开户名校验
                            if (!this.form.bank_account_name) {
                               this.$u.toast('请输入银行开户名！')
                               return
                            }
                            // 银行开户行校验
                            if (!this.form.bank_deposit_name) {
                                this.$u.toast('请输入银行开户行！')
                                return
                            }
                        } else if (this.form.account_type === 'ALIPAY' || this.form.account_type === 'WEIXINPAY' ){
                            // 退款账号校验
                            if (!this.form.return_account) {
                                this.$u.toast('请输入退款账号！')
                                return
                            }
                        }
                    }
                }
                if (!this.form.addrs) {
                    this.$u.toast('请选择收货地址！')
                    return
                }
                if (!this.form.ship_addr) {
                    this.$u.toast('请输入详细地址！')
                    return
                }
                if (!this.form.ship_name) {
                    this.$u.toast('请输入联系人！')
                    return
                }
                if (!this.form.ship_mobile || !RegExp.mobile.test(this.form.ship_mobile)) {
                    this.$u.toast('请输入正确格式的手机号码！')
                    return
                }
                return true
            }
        }
	}
</script>

<style lang="scss">
    .goods-view {
        background-color: #FFFFFF;
        padding: 15rpx;
        border-radius: 0rpx 0rpx 10rpx 10rpx;
    }
    .block-view {
        background-color: #FFFFFF;
        border-radius: 10rpx;
        margin: 10rpx 0rpx;
    }
    .btn-view {
        padding: 0rpx 30rpx;
        margin-top: 60rpx;
        margin-bottom: 40rpx;
    }
    .block-popup {
        .header {
            padding: 20rpx;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
            font-weight: 600;
        }
        .body {
            padding: 20rpx 30rpx;
            .title {
                font-weight: 600;
            }
            .value {
                display: flex;
                flex-direction: column;
                .radio-view {
                    margin: 10rpx 0rpx;
                }
            }
        }
        .footer {
            padding: 0rpx 20rpx;
        }
    }
</style>
